<template>
    <div>
            <div class="">
                <!--<p class="addRole-p"><span>快捷链接:</span><span>用户管理</span></p>-->
                <Form ref="addForm" :model="addForm" :rules="ruleValidate" :label-width="80">
                    <FormItem label="角色名称:" prop="roleName">
                        <Input type="text" clearable style="width: 240px" placeholder="请输入角色名称" v-model="addForm.roleName" :maxlength="255"></Input>
                    </FormItem>
                    <FormItem label="角色状态:" prop="enableStatus">
                        <Select v-model="addForm.enableStatus" clearable style="width:240px">
                            <Option v-for="item in modulesOpt" :value="item.value" :key="item.value">{{ item.label }}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="角色类型:" prop="roleType">
                        <Select v-model="addForm.roleType" clearable style="width:240px">
                            <Option v-for="item in modulesOpts" :value="item.value" :key="item.value">{{ item.label }}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="选择部门:" prop="orgStructId">
                        <Select v-model="addForm.orgStructId" clearable style="width:240px">
                            <Option v-for="item in modulesOptss" :value="item.value" :key="item.value">{{ item.label }}</Option>
                        </Select>
                    </FormItem>
                    <div style="width: 500px;">
                    <Form-item label="备注" prop="comment">
                        <i-input v-model="addForm.comment" clearable type="textarea" placeholder="请输入..." :maxlength="255"></i-input>
                    </Form-item>
                    </div>
                    <div>
                    <div>
                        <Tabs type="card" :animated="false">
                        <Tab-pane label="关联权限">
                            <div class="addRole-box">
                                <div class="roleTrees" v-model="addForm.menuCodes"  style="margin-left: 16px;padding-top: 16px;margin-top: -16px;">
                                    <Tree :data="dataTrees" show-checkbox ref="trees" @on-check-change="treesChanges" :render="renderContent"></Tree>
                                    <div class="clear" style="clear: both;"></div>
                                </div>
                            </div>
                        </Tab-pane>
                        <Tab-pane label="事件订阅">
                            <div class="addRole-box">
                                <div class="eventTree" v-model="addForm.roleEvents" style="margin-left: 30px;padding-top: 16px;margin-top: -16px;">
                                    <Tree :data="dataTree" show-checkbox ref="tree"></Tree>
                                    <div class="clear" style="clear: both;"></div>
                                </div>
                            </div>
                        </Tab-pane>
                    </Tabs>
                    </div>
                    </div>
                </Form>
            </div>
            <div slot="footer">
                <Button type="primary" size="large" @click="saveForm('addForm')" class="margin-top-20">保存设置</Button>
            </div>
    </div>
</template>

<script>
    import { getfunMenuApi ,getEventMenuApi } from '../../http/functionView.api'
    import {addRoleApi ,getOrg_structApi } from '../../http/role.api'
    import _ from "undersocre"
    export default {
        name: 'addRole',
        props: {
            itemOpt: {
                type: Array
            }
        },
        data () {
            return {
                spinShow: false,
                treeCheck: false,
                dataTrees: [
                    {
                        title: '用户管理',
                        expand: true,
                        render: (h, { root, node, data }) => {
                            return h('span',
                                [
                                h('span', [h('span', data.title)
                                ])
                            ]);
                        },
                        children: [
                            {
                                title: '系统设置',
                                expand: true,
                                children: [
                                    {
                                        /*title: '权限管理',
                                        expand: true,
                                        children: [
                                            {
                                                title: '查看权限'
                                            }
                                        ]*/
                                        title: '权限管理'
                                    }
                                ]
                            }
                        ]
                    }
                ],
                dataTree: [
                    {
                        title: '用户管理',
                        expand: true,
                        children: [
                            {
                                title: '系统设置',
                                expand: true,
                                children: [
                                    {
                                        /*title: '权限管理',
                                        expand: true,
                                        children: [
                                            {
                                                title: '查看权限'
                                            }
                                        ]*/
                                        title: '权限管理'
                                    }
                                ]
                            }
                        ]
                    }
                ],
                ruleValidate: {
                    roleName: [
                        { required: true, message: '角色名称不能为空', trigger: 'blur' },
                        { max: 255, message: '最多输入255个字符', trigger: 'blur' }
                    ],
                    enableStatus: [
                        { required: true, message: '角色状态不能为空', trigger: 'blur' }
                    ],
                    roleType: [
                        { required: true, message: '角色类型不能为空', trigger: 'blur' }
                    ],
                   /* orgStructId: [
                        { required: true, message: '选择部门不能为空', trigger: 'blur' }
                    ],*/
                    comment: [
                        { required: true, message: '备注不能为空', trigger: 'blur' },
                        { max: 255, message: '最多输入255个字符', trigger: 'blur' }
                    ]
                },
                formItem: {
                    input: '',
                    select: '',
                    radio: 'male',
                    checkbox: [],
                    switch: true,
                    date: '',
                    time: '',
                    slider: [20, 50],
                    textarea: ''
                },
                addModal: false,
                modulesOpt: [
                    {
                        value: 'true',
                        label: '启用'
                    },
                    {
                        value: 'false',
                        label: '禁用'
                    }
                ],
                modulesOpts: [
                    {
                        value: 'general',
                        label: '普通角色'
                    },
                    {
                        value: 'system',
                        label: '系统角色'
                    }
                ],
                modulesOptss: [],
                addForm: {
                    roleName: '',
                    enableStatus: '',
                    roleType: '',
                    orgStructId: '',
                    comment: '',
                    menuCodes: [],
                    roleEvents: []

                }
            }
        },
        created () {
            this.spinShow = true
            getOrg_structApi().then(suc => {
                console.log('suc.data.result.===',suc.data.result[0].dept)
                suc.data.result.map(datas => {
                    this.modulesOptss.push({
                               value: datas.id,
                               label: datas.dept
                   })
               })
            })
            console.log("modulesOptss[]==="+this.modulesOptss)
            //没有二级菜单
            getfunMenuApi().then(suc => {
                function buildTree(tree) {
                    return {
                        title: tree.name,
                        expand: true,
                        children: tree.menuLists.map((item) => getNode(item))
                    }
                }
                function  getNode(item) {
                    let obj = {
                        title: item.name,
                        expand: true,
                        originVal: item
                    };
                    if (item.menuLists&&item.menuLists.length) {
                        obj.children = item.menuLists.map((item1) => getNodes(item1)); //getNode(item1)没有二级菜单
                    }
                    return obj;
                }

                /*console.log("123==========="+this.$refs.trees.getCheckedNodes())*/
                //有二级菜单
                function  getNodes(item1) {

                    let obj = {
                        title: item1.name,
                        expand: true,
                        originVal: item1
                    };
                    if (item1.menuItems&&item1.menuItems.length) {
                        /*console.log("treesChange==="+treesChange())*/
                        /*obj.children = item1.menuItems.map((item2) => ({title: item2.name+(item2.desc?"（"+item2.desc+"）":""), originVal: item2}));*/
                        obj.children = item1.menuItems.map((item2) => ({title: item2.name+(item2.desc?"（"+item2.desc+"）":""), originVal: item2}));
                        /*obj.children = item1.menuItems.map((item2) => ({title: item2.name+(item2.desc?"（"+item2.desc+"）":""), originVal: item2,checked:(item2.open===true)?true:false}));*/
                        /*obj.children = item1.menuItems.map((item2) => ({title: item2.name+(item2.desc?"（"+item2.desc+"）":""), originVal: item2,checked:(this.$refs.trees.getCheckedNodes())?((item2.open===true)?true:false):false}));*/


                    }
                    return obj;
                }

                /*this.dataTrees[0].children = suc.data.result[1].menuLists.map((item) => getNode(item))*/
                this.dataTrees = suc.data.result.map(tree => buildTree(tree))
                this.spinShow = false
            }).catch(err => {
                this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                this.spinShow = false
            })
            //事件
            getEventMenuApi().then(suc => {
              function  getEvent(item) {
                    let obj = {
                        title: item.name,
                        expand: true,
                        originVal: item
                    };
                    if (item.eventLists&&item.eventLists.length) {
                        obj.children = item.eventLists.map((item1) => getEvents(item1)); //getNode(item1)没有二级菜单
                    }
                    return obj;
                }
                function  getEvents(item1) {
                    let obj = {
                        title: item1.name,
                        expand: true,
                        originVal: item1
                    };
                    if (item1.eventItems&&item1.eventItems.length) {
                        obj.children = item1.eventItems.map((item2) => ({title: item2.name, originVal: item2}));
                       /* obj.children = item1.eventItems.map((item2) => ({title: item2.name+(item2.code?"（"+item2.code+"）":"")}));*/
                    }
                    return obj;
                }
                this.dataTree = suc.data.result.eventModules.map((item) => getEvent(item))
                this.spinShow = false
            }).catch(err => {
                this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                this.spinShow = false
            })
        },
        watch: {
            'addModal' (val) {
                console.log(this.itemOpt)
                if (val) this.formInit()
            }
        },
        methods: {
            // 获取勾选数组
            treesChanges (n) {
                /*console.log(n)*/
                let level3=this.dataTrees[1].children[0].children;
                for(let i=0,len=level3.length;i<len;i++) {
                    let item = level3[i].children;
                    let flag=false;
                        for (let j = 0, lenj = item.length; j < lenj; j++) {
                            let subItem = item[j];
                            if(n && _.findWhere(n,{nodeKey:subItem.nodeKey})){
                                flag=true;
                            }
                    }
                    if(flag){
                        for (let j = 0, lenj = item.length; j < lenj; j++) {
                            let subItem = item[j];

                        if (subItem.originVal && subItem.originVal.open) {
                            let hasView = _.findWhere(n, {nodeKey: subItem.nodeKey});
                            if (!hasView) {
                                subItem.checked = true;
                            }
                        }
                        }
                    }

                }
                /*let userRoles= _.findWhere(level3,{title:"角色管理"})
                let viewNode= _.findWhere(userRoles.children,{nodeKey:12});*/
//                let hasView = _.findWhere(n,{nodeKey:12});
//                if(n.length>0 && !hasView)
//                {
//                    viewNode.checked=true;
//                }
            },
            renderContent (h, { root, node, data }) {
                return h('span',
                    [
                    h('span', [
                        h('span', data.title)
                    ])
                ]);
            },
            formInit () {
                this.addForm = {
                    roleName: '',
                    enableStatus: '',
                    roleType: '',
                    orgStructId: '',
                    comment: '',
                    menuCodes: [],
                    roleEvents: []
                }
            },
            //子页面的保存
            saveForm (name) {
                this.addForm.menuCodes = this.$refs.trees.getCheckedNodes().filter(item => item&&(!item.children||!item.children.length)).map((item2) => (item2.originVal.code))
                this.$refs.tree.getCheckedNodes().filter(item => item&&(!item.children||!item.children.length)).map((item3) => this.addForm.roleEvents.push({eventCode: item3.originVal.code}))

                console.log("event[]======"+  JSON.stringify(this.addForm.roleEvents))
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.spinShow = true
                        addRoleApi(this.addForm).then(suc => {
                            this.addModal = false
                            this.$emit('emitAddPerSuc')
                            this.spinShow = false
                            this.$router.push('/role')
                            this.getPerTable()
                        }).catch(err => {
                            this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                            this.spinShow = false
                        })
                   }
                })
            }
        }
    }
</script>
<style>
.addRole-p span{
    display: inline-block;
    margin-left: 20px;
    padding-bottom: 20px;
    cursor: pointer;
    font-size: 14px;
}
.addRole-div{
    width:100%;
    padding-bottom: 10px;
    margin-bottom: 15px;
    border-bottom:1px solid #ccc;
}
.addRole-box{
    border: 1px solid #ccc;
    border-top: 0;
}
.addRole-boxs{
    border: 1px solid #ccc;
    margin-top: 20px;
}
    .margin-top-20{
        margin-top:20px;
    }
</style>
